package Servelt;

import DatabaseAccessing.ProductModelController;
import DatabaseAccessing.Productcategory;
import DatabaseAccessing.Products;
import javax.servlet.RequestDispatcher;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class AddProduct extends HttpServlet {

    //private static final String TMP_DIR_PATH = "/tmp";
    private static String TMP_DIR_PATH;
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "/productImages";
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        TMP_DIR_PATH = config.getServletContext().getRealPath("/tmp");
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ProductModelController controller = new ProductModelController();
        List<Productcategory> categories = controller.viewAllCategorys();

        RequestDispatcher rd = request.getRequestDispatcher("AddProduct.jsp");
        request.setAttribute("allCategories", categories);
        rd.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        ProductModelController controller = new ProductModelController();
        Products product = new Products();

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024);
        fileItemFactory.setRepository(tmpDir);
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        try {
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();

            while (itr.hasNext()) {

                FileItem item = (FileItem) itr.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("productName")) {
                        product.setProductName(item.getString());
                    } else if (item.getFieldName().equals("lstCategories")) {
                        product.setProductCategoryId(Integer.parseInt(item.getString()));
                    } else if (item.getFieldName().equals("productPrice")) {
                        product.setPrice(Float.parseFloat(item.getString()));
                    } else if (item.getFieldName().equals("productAmount")) {
                        product.setAmount(Integer.parseInt(item.getString()));
                    } else if (item.getFieldName().equals("productDescription")) {
                        product.setProductNotes(item.getString());
                    }


                } else {
                    product.setProductImage(item.getName());
                    File file = new File(destinationDir, item.getName());
                    item.write(file);
                }
            }

            controller.addProduct(product);

            RequestDispatcher rd = request.getRequestDispatcher("AddProductDone.jsp");
            request.setAttribute("message", "Product added successfully.");
            rd.forward(request, response);

        } catch (Exception exp) {
            RequestDispatcher rd = request.getRequestDispatcher("AddProductDone.jsp");
            request.setAttribute("message", "Error: Couldn't add this product, Please try again later.");
            rd.forward(request, response);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Add Product to the DataBase";
    }// </editor-fold>
}
